package com.tanhua.server;

import cn.hutool.core.collection.CollUtil;
import com.itheima.commons.utils.Constants;
import com.tanhua.autoconfig.template.FaceTemplate;
import com.tanhua.autoconfig.template.OssTemplate;
import com.tanhua.dubbo.api.*;
import com.tanhua.exception.BusinessException;
import com.tanhua.interceptor.UserHolder;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.mongo.Friend;
import com.tanhua.model.mongo.RecommendUser;
import com.tanhua.model.mongo.UserLike;
import com.tanhua.model.mongo.Visitors;
import com.tanhua.model.vo.CountsLikeVo;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.UserInfoVo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class UserInfoService {
    @DubboReference
    private UserInfoApi userInfoApi;
    @Autowired
    private OssTemplate ossTemplate;
    @Autowired
    private FaceTemplate faceTemplate;
    @DubboReference
    private FriendApi friendApi;
    @DubboReference
    private FocusUserApi focusUserApi;
    @DubboReference
    private VisitorsApi visitorsApi;
    @DubboReference
    private RecommendUserApi recommendUserApi;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @DubboReference
    private UserLikeApi userLikeApi;


    public void save(UserInfo userInfo) {
        userInfoApi.save(userInfo);
    }

    public void updateHead(MultipartFile headPhoto, Long id) throws IOException {
        String originalFilename = headPhoto.getOriginalFilename();
        InputStream inputStream = headPhoto.getInputStream();

        String imgUrl = ossTemplate.upload(originalFilename, inputStream);
        boolean detect = faceTemplate.detect(imgUrl);
        if (!detect) {
            throw new BusinessException(ErrorResult.faceError());
        } else {
            UserInfo userInfo = new UserInfo();
            userInfo.setId(id);
            userInfo.setAvatar(imgUrl);
            userInfoApi.update(userInfo);
        }

    }

    public UserInfoVo getById(long id) {
        UserInfo userInfo = userInfoApi.getById(id);
        UserInfoVo infoVo = new UserInfoVo();
        BeanUtils.copyProperties(userInfo, infoVo);
        if (infoVo.getAge() == null && userInfo.getAge() != null) {
            infoVo.setAge(userInfo.getAge().toString());
        }
        return infoVo;
    }

    public void updateUsers(UserInfo userInfo) {
        userInfoApi.update(userInfo);
    }

    public void updateHeaders(MultipartFile headPhoto) throws IOException {
        Long userId = UserHolder.getUserId();
        String filename = headPhoto.getOriginalFilename();
        InputStream inputStream = headPhoto.getInputStream();
        String imgUrl = ossTemplate.upload(filename, inputStream);
        userInfoApi.updateHeadersById(userId, imgUrl);
    }

    //互相喜欢、喜欢、粉丝、谁看过我 - 翻页列表
    public PageResult ListByType(Integer page, Integer pagesize, Integer type, String nickname) {
        Long userId = UserHolder.getUserId();
        if (nickname != null) {
            UserInfo userInfo = userInfoApi.findByNickname(nickname);
            userId = userInfo.getId();
        }
        List<Long> ids = null;
        if (type == 1) {
            List<Friend> friends = friendApi.getByUserId(userId, page, pagesize);
            ids = CollUtil.getFieldValues(friends, "friendId", Long.class);
        } else if (type == 2) {
            List<UserLike> userLikes = userLikeApi.findById(userId, true, page, pagesize);
            ids = CollUtil.getFieldValues(userLikes, "likeUserId", Long.class);
        } else if (type == 3) {
            List<UserLike> userLikes = userLikeApi.findFans(userId, page, pagesize);
            ids = CollUtil.getFieldValues(userLikes, "userId", Long.class);
        } else if (type == 4) {
            List<Visitors> visitors = visitorsApi.findById(userId);
            ids = CollUtil.getFieldValues(visitors, "visitorUserId", Long.class);
            String key = Constants.VISITORS;
            String hashKey = userId.toString();
            String value = String.valueOf(System.currentTimeMillis());
            redisTemplate.opsForHash().put(key, hashKey, value);
        }
        if (CollUtil.isEmpty(ids)) {
            return new PageResult();
        }
        Map<Long, UserInfo> userInfoMap = userInfoApi.getByIds(ids, null);
        ArrayList<UserInfo> userInfos = new ArrayList<>(userInfoMap.values());
        Long finalId = userId;
        userInfos.forEach(userInfo -> {
            if (focusUserApi.exist(finalId, userInfo.getId())) {
                userInfo.setAlreadyLove(true);
            }
            RecommendUser recommendUser = recommendUserApi.getByToUserId(userInfo.getId(), finalId);
            if (recommendUser != null) {
                userInfo.setMatchRate(recommendUser.getScore().intValue());
            }
        });
        PageResult pageResult = new PageResult();
        pageResult.setItems(userInfos);
        pageResult.setPage(page);
        pageResult.setPagesize(pagesize);
        pageResult.setCounts((long) userInfos.size());
        return pageResult;
    }

    public CountsLikeVo getCounts() {
        Long userId = UserHolder.getUserId();
        List<Friend> friends = friendApi.getByUserId(userId, null, null);
        List<UserLike> userLikes = userLikeApi.findById(userId,true,null,null);
        List<UserLike> fans = userLikeApi.findFans(userId, null,null);
        CountsLikeVo countsLikeVo = new CountsLikeVo();
        countsLikeVo.setEachLoveCount(friends.size());
        countsLikeVo.setLoveCount(userLikes.size());
        countsLikeVo.setFanCount(fans.size());
        return countsLikeVo;
    }

    /**
     * type:
     * 1 互相关注
     * 2 我关注
     * 3 谁关注我
     * 4 谁看过我
     */
    /*public PageResult ListByType(Integer page, Integer pagesize, Integer type,String nickname) {
        Long id = UserHolder.getUserId();
        if (nickname != null) {
            UserInfo userInfo = userInfoApi.findByNickname(nickname);
            id = userInfo.getId();
        }
        PageResult pageResult = new PageResult();
        List<Long> userIds = null;
        if (type == 1) {
            List<Friend> friends = friendApi.getByUserId(id, page, pagesize);
            userIds = CollUtil.getFieldValues(friends, "friendId", Long.class);
        } else if (type == 2) {
            List<FocusUser> focusUsers = focusUserApi.getByUserId(id, page, pagesize);
            userIds = CollUtil.getFieldValues(focusUsers, "followUserId", Long.class);
        } else if (type == 3) {
            List<FocusUser> fans = focusUserApi.getFans(id, page, pagesize);
            userIds = CollUtil.getFieldValues(fans, "userId", Long.class);
        } else if (type == 4) {
            List<Visitors> visitors = visitorsApi.findById(id);
            userIds = CollUtil.getFieldValues(visitors, "visitorUserId", Long.class);
                String key = Constants.VISITORS;
                String hashKey = id.toString();
                String value = String.valueOf(System.currentTimeMillis());
                redisTemplate.opsForHash().put(key, hashKey, value);
        }
        if (CollUtil.isEmpty(userIds)) {
            return new PageResult();
        }
        Map<Long, UserInfo> infoMap = userInfoApi.getByIds(userIds, null);

        List<UserInfo> userInfos = new ArrayList<>(infoMap.values());
        Long finalId = id;
        userInfos.forEach(userInfo -> {
            if (focusUserApi.exist(finalId, userInfo.getId())) {
                userInfo.setAlreadyLove(true);
            }
            RecommendUser recommendUser = recommendUserApi.getByToUserId(userInfo.getId(), finalId);
            if (recommendUser != null) {
                userInfo.setMatchRate(recommendUser.getScore().intValue());
            }
        });

        pageResult.setItems(userInfos);
        pageResult.setPage(page);
        pageResult.setPagesize(pagesize);
        pageResult.setCounts((long) userInfos.size());
        return pageResult;
    }

    public CountsLikeVo getCounts() {
        Long userId = UserHolder.getUserId();
        List<Friend> friends = friendApi.getByUserId(userId, null, null);
        List<FocusUser> focusUsers = focusUserApi.getByUserId(userId, null, null);
        List<FocusUser> fans = focusUserApi.getFans(userId, null, null);
        CountsLikeVo countsLikeVo = new CountsLikeVo();
        countsLikeVo.setEachLoveCount(friends.size());
        countsLikeVo.setLoveCount(focusUsers.size());
        countsLikeVo.setFanCount(fans.size());
        return countsLikeVo;
    }*/


}
